# -*- coding:utf-8 -*-
import jinja2
import sys, getopt, os, time
from jinja2 import Environment, FileSystemLoader
import yaml
try:
    from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
    from yaml import Loader, Dumper

class Updateapp(object):
    def __init__(self, appname, registry, version, namespace="dev", nodeselectorname="dev", nodeselectorvalues="dev2", publishenv="dev", recpu=1, rememory="1G", licpu=1, limemory="1G", portdict={"rellip": "8080"}, envdict={"envname": "cpu"}, approuter="true", replicas=2, initialDelay="30", healthurl="/health"):
        self.namespace=namespace
        self.appname=appname
        self.nodeselectorname = nodeselectorname
        self.nodeselectorvalues = nodeselectorvalues
        self.registry = registry
        self.version = version
        self.publishenv = publishenv
        self.recpu = recpu
        self.rememory = rememory
        self.licpu = licpu
        self.limemory = limemory
        self.portdict = portdict
        self.envdict = envdict
        self.approuter = approuter
        self.replicas = replicas
        self.initialDelay = initialDelay
        self.healthurl = healthurl
        self.base_dir = os.path.split(os.path.realpath(__file__))[0]
        self.template_dir = "app_template"
        self.app_common_template = "app_common_template.yaml"

    def getmetadata(self):
        content = {}
        #filePath = os.path.dirname(__file__)
        fileNamePath = os.path.split(os.path.realpath(__file__))[0]
        yamlPath = os.path.join(fileNamePath, 'pro_metadata/base-efssc_cicd.yaml')
        f = open(yamlPath,'r')
        cont = f.read()
        x = yaml.load(cont)
        print(type(x))
        content["appreplicas"] = x["spec"]["replicas"]
        content["router"] = x["spec"]["needRoute"]
        content["apphealthurl"] = x["spec"]["healthCheckPath"]
        content["apprelicpu"] = x["spec"]["resources"]["limits"]["cpu"]
        content["apprelime"] = x["spec"]["resources"]["limits"]["memory"]
        content["apprequcpu"] =  x["spec"]["resources"]["requests"]["cpu"] 
        content["apprequme"] = x["spec"]["resources"]["requests"]["memory"]
        content["appenv"] = x["spec"]["envVar"]
        return content

    def generate_yaml(self):
        filename = self.app_common_template
        path = "%s/%s"%(self.base_dir,self.template_dir)
        #path = self.template_dir
        loader = FileSystemLoader(path)
        env = Environment(loader=loader)
        template = env.get_template(filename)
        return template.render(appname=self.appname, registry=self.registry, version=self.version, namespace=self.namespace, nodeselectorname=self.nodeselectorname, nodeselectorvalues=self.nodeselectorvalues, publishenv=self.publishenv, recpu=self.recpu, rememory=self.rememory, licpu=self.licpu, limemory=self.limemory, envdict=self.envdict, portdict=self.portdict, approuter=self.approuter, replicas=self.replicas, initialDelay=self.initialDelay,healthcheckurl=self.healthurl)

    def write_yaml(self, yaml):
        if os.path.isdir("{base_dir}/yaml".format(base_dir=self.base_dir)):
            print("yaml dir is exist")
        else:
            os.mkdir("{base_dir}/yaml".format(base_dir=self.base_dir))
        file = "{base_dir}/yaml/{appname}.yaml".format(base_dir=self.base_dir, appname=self.appname)
        with open(file, 'w') as fp:
            fp.write(yaml)

    def add_yaml(self):
        dep = []
        file = "{base_dir}/yaml/{appname}.yaml".format(base_dir=self.base_dir, appname=self.appname)
        with open(file, "r") as f:
            for i in yaml.load_all(f.read()):
               dep.append(i)
            if self.appname.endswith("static"):
                pass
               # dep[0]["spec"]["template"]["spec"]["containers"][0]["env"].append({'name': 'WEB_MONITOR', 'value': 'uatstable.ihr360.com'})
               # dep[0]["spec"]["template"]["spec"]["containers"][0]["env"].append({'name': 'ihr360.config.region', 'value': 'default'})
               # dep[0]["spec"]["template"]["spec"]["containers"][0]["env"].append({'name': 'spring.profiles.active', 'value': 'prod'})
               # dep[0]["spec"]["template"]["spec"]["containers"][0]["env"].append({'name': 'ihr360.config.brand', 'value': 'uatstable'})
            else:
                pass
               # dep[0]["spec"]["template"]["spec"]["containers"][0]["env"].append({'name': 'WEB_MONITOR', 'value': 'uatstable.ihr360.com'})
               # dep[0]["spec"]["template"]["spec"]["containers"][0]["env"].append({'name': 'ihr360.config.region', 'value': 'default'})
        return dep
    
    def writes_yaml(self, yamls):
        new_content = yaml.dump_all(yamls, Dumper=Dumper, default_flow_style=False)
        print(new_content)
        file = "{base_dir}/yaml/{appname}.yaml".format(base_dir=self.base_dir, appname=self.appname)
        with open(file, 'w+') as fp:
            fp.write(new_content)

    def deploy_app(self):
        app_yaml="{base_dir}/yaml/{appname}.yaml".format(base_dir=self.base_dir, appname=self.appname)
        os.popen("kubectl delete -f %s" % app_yaml)
        print("#####delete success####")
        time.sleep(15)
        os.popen("kubectl apply -f %s --record" % app_yaml)
        time.sleep(5)
        print("#####deploy sucess###")

if __name__=='__main__':
    s = {}
    print(len(sys.argv))
#    yaml.warnings({'YAMLLoadWarning': False})
    if len(sys.argv) != 9:
        print("usage: python %s -v version -a appname -n namespace  -p publishenv" %sys.argv[0])
        sys.exit("parameter error")
    else:
        try:
            ops, args = getopt.getopt(sys.argv[1:], "hv:a:n:p:", ["help", "version=", "appname=", "namespace=", "publishenv="])
            for o, a in ops:
                if o in ("-h", "--help"):
                    print("usage: python %s -v version -a appname -n namespace -p publishenv" % sys.argv[0])
                    sys.exit()
                if o in ("-v", "--version"):
                    version = a
                    s["version"] = version

                if o in ("-a", "--appname"):
                    appname = a
                    s["appname"] = appname

                if o in ("-n", "--namespace"):
                    namespace = a
                    s["namespace"] = namespace

                if o in ("-p", "--publishenv"):
                    publishenv = a
                    s["publishenv"] = publishenv
        except getopt.GetoptError:
            print("error")
    version = s["version"]
    appname = s["appname"]
    registry = "harbor.assistfc.com"
    content = {}
    #filePath = os.path.dirname(__file__)
    fileNamePath = os.path.split(os.path.realpath(__file__))[0]
    yamlPath = os.path.join(fileNamePath, '../pro_metadata/base-efssc_cicd.yaml')
    f = open(yamlPath,'r')
    cont = f.read()
    x = yaml.load(cont)
    print(type(x))
    content["appreplicas"] = x["spec"]["replicas"]
    content["router"] = x["spec"]["needRoute"]
    content["apphealthurl"] = x["spec"]["healthCheckPath"]
    content["apprelicpu"] = x["spec"]["resources"]["limits"]["cpu"]
    content["apprelime"] = x["spec"]["resources"]["limits"]["memory"]
    content["apprequcpu"] =  x["spec"]["resources"]["requests"]["cpu"]
    content["apprequme"] = x["spec"]["resources"]["requests"]["memory"]
    content["appenv"] = x["spec"]["envVar"]
    print(content)
   # s = Updateapp(appname, registry, version, namespace="uatstable", nodeselectorname="uatstable", nodeselectorvalues="node-uatstable", publishenv="dev", recpu=2, rememory="2G", licpu=2, limemory="2G", envdict={"envname": "test"}, portdict={"rellport1": "8080"}, approuter="false", replicas=2, healthurl="/health")
    s = Updateapp(appname, registry, version, namespace=s["namespace"], nodeselectorname="uatstable", nodeselectorvalues="node-uatstable", publishenv=s["publishenv"], recpu=content["apprequcpu"], rememory=content["apprequme"], licpu=content["apprelicpu"], limemory=content["apprelime"], envdict=content["appenv"], portdict={"rellport1": "8080"}, approuter=content["router"], replicas=content["appreplicas"], healthurl=content["apphealthurl"])
    yml = s.generate_yaml()
    s.write_yaml(yml)
    t = s.add_yaml()
    s.writes_yaml(t)
   # s.deploy_app()

